package com.yfp.group.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.math.Money;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.binarywang.wxpay.bean.notify.WxPayPartnerNotifyV3Result;
import com.github.binarywang.wxpay.bean.notify.WxPayPartnerRefundNotifyV3Result;
import com.github.binarywang.wxpay.bean.result.WxPayUnifiedOrderV3Result;
import com.hy.corecode.idgen.WFGIdGenerator;
import com.yfp.common.core.constant.SecurityConstants;
import com.yfp.common.core.domain.R;
import com.yfp.common.core.exception.ServiceException;
import com.yfp.common.core.utils.bean.BeanUtils;
import com.yfp.common.core.web.domain.AjaxResult;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.group.domain.Enterprise;
import com.yfp.group.domain.dto.CreateWxPayOrderDTO;
import com.yfp.group.domain.dto.EnterpriseAccountDTO;
import com.yfp.group.domain.dto.EnterpriseUserDTO;
import com.yfp.group.domain.dto.GroupRegisterDTO;
import com.yfp.group.domain.vo.EnterpriseAccountVO;
import com.yfp.group.domain.vo.EnterpriseOrderQrCodeInfoVO;
import com.yfp.group.domain.vo.EnterpriseUserVO;
import com.yfp.group.enums.RegisterPayStatusEnums;
import com.yfp.group.enums.RegisterStatusEnums;
import com.yfp.group.enums.WxPayAttach;
import com.yfp.group.mapper.EnterpriseMapper;
import com.yfp.group.service.EnterpriseOrderService;
import com.yfp.group.service.EnterpriseService;
import com.yfp.group.service.PayService;
import com.yfp.system.api.RemoteUserService;
import com.yfp.system.api.domain.SysUser;
import com.yfp.system.api.model.LoginUser;
import com.yfp.tissue.api.RemoteCompanyService;
import com.yfp.tissue.domain.Company;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;

/**
 * @author admin
 * @description 针对表【enterprise_user(企业用户)】的数据库操作Service实现
 * @createDate 2024-08-10 09:44:34
 */
@Slf4j
@Service
public class EnterpriseServiceImpl extends ServiceImpl<EnterpriseMapper, Enterprise> implements EnterpriseService {

    @Resource
    private EnterpriseMapper enterpriseMapper;
    @Resource
    private RemoteCompanyService remoteCompanyService;
    @Resource
    private WFGIdGenerator wfgIdGenerator;
    @Resource
    private PayService payService;
    @Resource
    private WFGIdGenerator wFGIdGenerator;
    @Resource
    private RemoteUserService remoteUserService;
    @Resource
    private EnterpriseOrderService enterpriseOrderService;

    /**
     * 获取企业商户列表
     *
     * @return
     */
    @Override
    public List<EnterpriseUserVO> enterpriseUserList(EnterpriseUserDTO enterpriseUserDTO) {
        return enterpriseMapper.enterpriseUserList(enterpriseUserDTO);
    }

    /**
     * 根据id获取数据
     *
     * @param id
     * @return
     */
    @Override
    public Enterprise selectById(Long id) {
        Enterprise enterprise = enterpriseMapper.getById(id);
        return enterprise;
    }

    /**
     * 修改企业用户
     *
     * @param enterprise
     */
    @Override
    @Transactional
    public void updateEnterpriseUser(Enterprise enterprise) {

        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
//        Long userId = 58L;
        long next = wfgIdGenerator.next();

        // 原有数据
        Enterprise enterprise1 = enterpriseMapper.getById(enterprise.getId());
        Integer status = enterprise.getStatus();
        if (status != null && status == 2) {
            R<LoginUser> userInfoByPhone = remoteUserService.getOperationUserInfoByPhone(enterprise1.getContactsMobile(), SecurityConstants.INNER);
            Long id = null;
            if (null != userInfoByPhone.getData()){
                // 编辑
                AjaxResult ajaxResult = null;
                log.info("enterprise1：{}", enterprise1);
                if (userInfoByPhone.getData().getSysUser().getUserId().equals(enterprise1.getUserId())){
                    SysUser sysUser = new SysUser();
                    BeanUtils.copyProperties(userInfoByPhone.getData().getSysUser(), sysUser);
                    sysUser.setUserName(enterprise.getContactsMobile());
                    sysUser.setNickName(enterprise.getContacts());
                    sysUser.setPhonenumber(enterprise.getContactsMobile());
                    ajaxResult = remoteUserService.edit(sysUser);
                    log.info("ajaxResult：{}", ajaxResult);
                    if (!ajaxResult.isSuccess()) {
                        throw new ServiceException(ajaxResult.get("msg").toString());
                    }
                } else {
                    throw new ServiceException("号码已被账号使用！");
                }
            } else {
                // 新增
                SysUser sysUser = new SysUser();
                sysUser.setCompanyId(String.valueOf(next));
                // 默认密码
                sysUser.setNickName(enterprise.getContacts());
                sysUser.setPhonenumber(enterprise.getContactsMobile());
                sysUser.setStatus("0");
                sysUser.setUserName(enterprise.getContactsMobile());
                R<Long> longR = remoteUserService.addUser(sysUser);
                id = longR.getData();
                if (id == null) {
                    throw new ServiceException("号码已是企业商户！");
                }
            }
            R<Company> companyR = remoteCompanyService.findByCompanyAccount(enterprise1.getContactsMobile());
            Company company1 = companyR.getData();
            // 添加公司
            Company company = new Company();
            if (null != company1){
                // 编辑公司
                company1.setMobile(enterprise.getContactsMobile());
                company1.setCompanyAccount(enterprise.getContactsMobile());
                company1.setBizLicence(enterprise.getBusinessLicense());
                company1.setName(enterprise.getEnterpriseName());
                company1.setContacts(enterprise.getContacts());
                remoteCompanyService.updateCompany(company1);
            } else {
                company.setCompanyId(String.valueOf(next));
                company.setName(enterprise.getEnterpriseName());
                company.setBizLicence(enterprise.getBusinessLicense());
                company.setContacts(enterprise.getContacts());
                company.setMobile(enterprise.getContactsMobile());
                company.setGroupMeal(1);
                company.setContacts(enterprise.getContacts());
                remoteCompanyService.add(company);
            }


            enterprise.setUserId(id);
            enterprise.setAuditUserId(userId);
            // 同一个手机号只能通过一个，其他的拒绝
            enterpriseMapper.audit(enterprise);
        }
        enterprise.setUpdateUserId(userId);
        enterpriseMapper.updateEnterpriseUser(enterprise);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WxPayUnifiedOrderV3Result.JsapiResult register(GroupRegisterDTO groupRegisterBody) {
        // 初始参数数据
        Enterprise enterprise = BeanUtil.toBean(groupRegisterBody, Enterprise.class);

        // 检测改手机号是否注册过
        Boolean isActivateUser = this.checkActivateUser(groupRegisterBody.getContactsMobile());
        Assert.isFalse(isActivateUser, "该手机号已激活");

        // 封装注册数据
        DateTime dateTime = DateUtil.date();
        enterprise.setPayMoney(new Money(20_000).getAmount());
        // enterprise.setPayMoney(new Money(0.01).getAmount());
        enterprise.setBalance(new Money(0).getAmount());
        enterprise.setStatus(RegisterStatusEnums.UNAUDITED.getCode());
        enterprise.setCreateTime(dateTime);
        enterprise.setUpdateTime(dateTime);

        // 保证金支付方式1微信2其他方式
        if (1 == enterprise.getPayWay()) {
            String outTradeNo = String.valueOf(wFGIdGenerator.next());
            enterprise.setOrderSn(outTradeNo);
            enterprise.setPayStatus(RegisterPayStatusEnums.WAIT_PAY.getCode());
            // 插入注册数据
            enterpriseMapper.insert(enterprise);

            CreateWxPayOrderDTO createWxPayOrderDTO = new CreateWxPayOrderDTO();
            createWxPayOrderDTO.setDescription("团餐保证金");
            createWxPayOrderDTO.setOutTradeNo(outTradeNo);
            createWxPayOrderDTO.setTimeExpire(dateTime.offset(DateField.MINUTE, 30));
            createWxPayOrderDTO.setTotalPrice(enterprise.getPayMoney());
            createWxPayOrderDTO.setOpenid(enterprise.getOpenId());
            createWxPayOrderDTO.setSubMchId("1708356717");
            createWxPayOrderDTO.setAttach(WxPayAttach.REGISTER_PAY.getCode());
            // 调用微信支付
            return payService.createWxJsapiPayOrder(createWxPayOrderDTO);
        }
        // 保证金支付方式1微信2其他方式
        else if (2 == enterprise.getPayWay()) {
            enterprise.setPayStatus(RegisterPayStatusEnums.PAID.getCode());
            enterpriseMapper.insert(enterprise);
            return null;
        }

        throw new ServiceException("支付方式错误");
    }

    @Override
    public Enterprise findByUserId(Long userId) {
        return enterpriseMapper.findByUserId(userId);
    }

    @Override
    public void parseOrderNotifyResult(WxPayPartnerNotifyV3Result.DecryptNotifyResult result) {
        Enterprise enterprise = new Enterprise();
        enterprise.setOrderSn(result.getOutTradeNo());
        enterprise.setPayStatus(RegisterPayStatusEnums.PAID.getCode());
        enterprise.setTransactionId(result.getTransactionId());
        enterpriseMapper.updateByOrderSn(enterprise);
    }

    @Override
    public void parseRefundNotifyResult(WxPayPartnerRefundNotifyV3Result.DecryptNotifyResult result) {

    }

    @Override
    public EnterpriseAccountVO getByCurrentUserId() {
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getLoginUser().getUsername();

        // 根据用户id查询企业信息
        Enterprise enterprise = enterpriseMapper.findByUserId(userId);
        EnterpriseAccountVO enterpriseAccountVO = BeanUtil.toBean(enterprise, EnterpriseAccountVO.class);
        // 获取企业订单二维码信息
        EnterpriseOrderQrCodeInfoVO enterpriseOrderQrCodeInfoVO = enterpriseOrderService.orderQrCodeInfo();
        enterpriseAccountVO.setEnterpriseOrderQrCodeInfoVO(enterpriseOrderQrCodeInfoVO);
        // 获取用户头像
        R<LoginUser> userResult = remoteUserService.getGroupUserInfoByPhone(username, SecurityConstants.INNER);
        if (R.SUCCESS == userResult.getCode()) {
            String avatar = Optional.ofNullable(userResult.getData().getSysUser().getAvatar())
                    .orElse("https://obs-yfp.qafanle.com/applet/head_img01.svg");
            enterpriseAccountVO.setAvatarUrl(avatar);
        }
        return enterpriseAccountVO;
    }

    @Override
    public Boolean checkActivateUser(String contactsMobile) {
        long l = enterpriseMapper.checkActivateUser(contactsMobile);
        return l > 0;
    }

    @Override
    public void updateAvatar(EnterpriseAccountDTO enterpriseAccountDTO) {
        String avatarUrl = enterpriseAccountDTO.getAvatarUrl();
        R<Void> voidR = remoteUserService.updateAvatar(avatarUrl, SecurityConstants.INNER);
        if (R.isError(voidR)) {
            throw new ServiceException("头像更新失败");
        }
    }

}




